const Service = require('egg').Service;
var WXBizDataCrypt = require('../wx/WXBizDataCrypt')

class UserService extends Service {

    async decrypt(appid, sessionKey, encryptedData, iv) {
        var pc = new WXBizDataCrypt(appid, sessionKey)
        var data = await pc.decryptData(encryptedData, iv)
        return data;
    }
    async seveToken() {
        const ctx = this.ctx;
        const {
            appid,
            apps
        } = ctx.app.config.wxKey
        const url = `https://api.weixin.qq.com/cgi-bin/token?appid=${appid}&secret=${apps}&grant_type=client_credential`
        const result = await ctx.app.curl(url, {
            dataType: 'json',
        });
        var nowTime = +new Date() / 1000
        var data = {
            nowTime,
            ...result.data
        }
        ctx.weixintoken = data
        return data
    }
    async getToken() {
        const ctx = this.ctx;

        var data = ctx.weixintoken;
        if (!data || (+new Date() / 1000) - data.nowTime > data.expires_in) {
            let resdata = await ctx.service.wx.seveToken()
            return resdata.access_token
        } else {
            return data.access_token
        }

    }
    async databaseCollectionGet() {
        const token = await this.ctx.service.wx.getToken();
        var url = `https://api.weixin.qq.com/tcb/databasecollectionget?access_token=${token}`
        const result = await this.ctx.curl(url, {
            // 必须指定 method
            method: 'POST',
            // 通过 contentType 告诉 HttpClient 以 JSON 格式发送
            contentType: 'json',
            data: {
                env: 'bmg-test-3gt5ubuu31d80104',
                limit: 10,
                offset: 0
            },
            // 明确告诉 HttpClient 以 JSON 格式处理返回的响应 body
            dataType: 'json',
        });
        return result.data
    }
}

module.exports = UserService;